<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      title="选择场馆"
      width="52%"
      :show-close="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <el-row>
        <el-col :span="4">
          <div class="left_card">
            <div class="select_city">
              <el-cascader
                filterable
                clearable
                :show-all-levels="false"
                placeholder="请选择区域"
                :options="filteredOptions"
                v-model="addressId"
                @change="handleChange"
              ></el-cascader>
            </div>
            <div class="left_area">
              <div
                :class="['area_btn', { active: selectArea === item.value }]"
                v-for="item in districtList"
                :key="item.value"
                @click="handleAreaClick(item)"
              >
                {{ item.label }}
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="20">
          <div class="right_card">
            <el-form :inline="true" label-position="left" label-width="70px">
              <el-form-item label="场馆类型">
                <el-select
                  filterable
                  clearable
                  v-model="queryParams.stadiumType"
                  placeholder="请选择场馆类型"
                  @change="handleQuery"
                >
                  <el-option
                    v-for="dict in siteTypeList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="queryParams.stadiumName"
                  placeholder="请输入场馆名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="text" @click="handleQuery">查询</el-button>
              </el-form-item>
            </el-form>
            <el-table
              ref="multipleTableRef"
              :data="list"
              v-loading="loading"
              :row-key="getRowKeys"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                :reserve-selection="true"
                type="selection"
                width="50"
              ></el-table-column>
              <el-table-column prop="stadiumName" label="场馆名称" show-overflow-tooltip />
              <el-table-column prop="stadiumType" label="类型" width="100" show-overflow-tooltip />
              <el-table-column prop="districtName" label="区域" width="120" show-overflow-tooltip />
              <el-table-column prop="address" label="地址" show-overflow-tooltip />
              <el-table-column prop="isBusiness" label="营业状态" width="100">
                <template #default="{ row }">
                  <div :class="['status', row.enable == 1 ? 'text-color-43CF7C' : 'status_red']">
                    <span>{{ row.enable == 1 ? '营业中' : '已停用' }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <pagination
              v-show="queryParams.total > 0"
              :total="queryParams.total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="handleQuery"
            />
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { useDict } from '@/utils/dict'
import { couponShowList } from '@/api/coupon/coupon'
import { getAreaTree } from '@/api/stadium/stadium'
import { ElMessage } from 'element-plus'

// 字典数据
const { dict } = useDict({
  dicts: ['site_type', 'discount_type', 'platform_type', 'sys_normal_disable'],
})

// 定义 emits
const emit = defineEmits(['refreshShow'])

// 定义响应式数据
const dialogVisible = ref(false)
const selectArea = ref('')
const areaTree = ref<any[]>([])
const addressId = ref(['10000009', '10000107'])
const districtList = ref<any[]>([])
const loading = ref(false)
const list = ref<any[]>([])
const selectData = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const multipleTableRef = ref()
const siteTypeList = ref<any[]>([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 1,
  stateId: '10000009',
  cityId: '10000107',
  districtId: '',
  stadiumName: '',
  stadiumType: null as string | null,
})

const filteredOptions = computed(() => {
  return areaTree.value.map((item) => ({
    ...item,
    children: item.children.map((child: any) => ({ ...child, children: null })),
  })) // 只保留省市区两级结构，移除子选项的子选项。
})

// 加载数据
const init = () => {
  dialogVisible.value = true
  // 整合场馆类型
  siteTypeList.value = dict.value.type.site_type
  siteTypeList.value.unshift({ value: '', label: '综合' })
  queryParams.pageNum = 1
  getArea()
  getStadium()
}

// 获取场馆列表
const getStadium = () => {
  loading.value = true
  couponShowList(queryParams)
    .then((res: any) => {
      loading.value = false
      list.value = res.rows
      queryParams.total = res.total
      nextTick(() => {
        if (multipleTableRef.value) {
          list.value.forEach((row) => {
            console.log(selectData.value)
            const selectRow = selectData.value.find((item: any) => item.id === row.id)
            multipleTableRef.value.toggleRowSelection(row, selectRow ? true : false)
          })
        }
      })
    })
    .catch(() => {
      loading.value = false
    })
}

// 获取省市区列表
const getArea = async () => {
  const res: any = await getAreaTree()
  areaTree.value = res.data
  getDistrictsByCityId(queryParams.cityId)
}

// 根据市 ID 获取区县列表
const getDistrictsByCityId = (cityId: string) => {
  const city = areaTree.value
    .flatMap((province: any) => province.children)
    .find((city: any) => city.value === cityId)
  if (city) {
    districtList.value = JSON.parse(JSON.stringify(city.children))
    districtList.value.unshift({ label: '不限', value: '' })
    selectArea.value = ''
    queryParams.districtId = ''
    getStadium()
  }
}

// 选择省市
const handleChange = (val: any) => {
  if (val && val.length >= 2) {
    queryParams.stateId = val[0]
    queryParams.cityId = val[1]
    districtList.value = []
    getDistrictsByCityId(queryParams.cityId)
  }
}

// 查询场馆
const handleQuery = () => {
  getStadium()
}

// 表格跨页多选
const getRowKeys = (row: any) => {
  return row.id
}

// 表格多选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  // emit("refreshShow", { type: "chooseStadium", applyStadium: [] });
}

const submitForm = () => {
  let checkList: any[] = []
  if (multipleSelection.value.length > 0) {
    checkList = multipleSelection.value.map((item: any) => item.id)
  } else {
    ElMessage.warning('请选择场馆')
    return
  }
  dialogVisible.value = false
  emit('refreshShow', {
    type: 'chooseStadium',
    applyStadium: checkList,
  })
  if (multipleTableRef.value) {
    multipleTableRef.value.clearSelection()
  }
}

// 点击区域
const handleAreaClick = (val: any) => {
  queryParams.districtId = val.value
  selectArea.value = val.value
  getStadium()
}

// 暴露方法给父组件
defineExpose({
  init,
})
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 0 38px 4px 0;
  .el-table thead tr th.el-table__cell {
    padding: 11px 0;
    font-size: 14px;
  }
  .pagination-container {
    margin-top: 13px;
  }
}
:deep(.el-cascader) {
  .el-input .el-input__inner {
    border: none;
    color: #383838;
    text-align: center;
  }
}
.left_btn {
  font-size: 14px;
  font-weight: 400;
  color: rgba(56, 56, 56, 1);
}

.left_card {
  text-align: center;
  background: rgba(255, 255, 255, 1);
  border-right: 1px solid #e5e5e5;
  overflow-y: auto;
  .select_city {
    margin: 8px 8px 0;
    border-bottom: 1px solid #e5e5e5;
  }
  .left_area {
    padding: 8px 27px 0;
    height: 525px;
    overflow-y: auto;
    cursor: pointer;
    .area_btn {
      font-size: 14px;
      font-weight: 400;
      height: 28px;
      line-height: 28px;
      color: rgba(56, 56, 56, 1);
      margin: 0 0 6px 0;
      border-radius: 3px;
      &.active {
        height: 28px;
        color: rgba(42, 130, 228, 1);
        background: rgba(42, 130, 228, 0.13);
      }
    }
  }
}

.right_card {
  margin: 8px 0 0 15px;
  .el-form {
    padding-left: 20px;
    .el-form-item {
      margin-bottom: 15px;
    }
  }
}

.status {
  display: flex;
  align-items: center;
  .dian {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
  }
  &.status_green {
    color: #0fbd66;
    .dian {
      background: #0fbd66;
    }
  }
  &.status_red {
    color: #d43030;
    .dian {
      background: #d43030;
    }
  }
}

:deep(.el-dialog__header) {
  border-radius: 6px 6px 0 0;
  background: rgba(243, 244, 246, 1);
  padding: 12px 15px;
  .el-dialog__title {
    font-size: 14px;
    color: #383838;
  }
}

:deep(.el-dialog__footer) {
  padding-bottom: 14px;
  padding-right: 57px;
}
</style>
